class Solution {
    vector<int> tmp;
public:
    int reversePairs(vector<int>& record) {
        tmp.resize(record.size());
        return mergeSortCnt(record, 0, record.size() - 1);
    }
 
    int mergeSortCnt(vector<int>& arr, int left, int right)
    {   // 解法二：找出该数之前，有多少个数比我小 -> 降序
        if(left >= right)
            return 0;
        int ret = 0, mid = (left + right) >> 1;
        // 左边逆序对的个数+排序 + 右边逆序对的个数+排序
        ret += mergeSortCnt(arr, left, mid);
        ret += mergeSortCnt(arr, mid + 1, right);
        // 一左一右逆序对的个数
        int cur1 = left, cur2 = mid + 1, i = 0;
        while(cur1 <= mid && cur2 <= right)
        {
            if(arr[cur1] > arr[cur2])
            {   // 此时cur2后面的都是比cur1小的
                // ret += mid - cur1 + 1;
                // tmp[i++] = arr[cur2++];
 
                ret += right - cur2 + 1;
                tmp[i++] = arr[cur1++]; // 降序
            }
            else
            {
                // tmp[i++] = arr[cur1++];
                tmp[i++] = arr[cur2++]; // 降序
            }
        }
        // 处理排序
		while (cur1 <= mid) 
            tmp[i++] = arr[cur1++];
		while (cur2 <= right) 
            tmp[i++] = arr[cur2++];
		for (int j = left; j <= right; j++)
			arr[j] = tmp[j - left];
        
        return ret;
    }
};